/**
 * Created by wust on 2020-04-18 11:01:08
 * Copyright © 2020 wust. All rights reserved.
 */
package com.sc.admin.core.bo;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.admin.core.dao.*;
import com.sc.admin.core.dao.*;
import com.sc.common.entity.admin.company.SysCompany;
import com.sc.common.entity.admin.department.SysDepartment;
import com.sc.common.entity.admin.organization.SysOrganization;
import com.sc.common.entity.admin.project.SysProject;
import com.sc.common.entity.admin.role.SysRole;
import com.sc.common.entity.admin.user.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @author: wust
 * @date: Created in 2020-04-18 11:01:08
 * @description:
 *
 */
@Component
public class OrganizationBo {
    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;

    @Autowired
    private UserOrganizationBo userOrganizationBo;

    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysProjectMapper sysProjectMapper;

    @Autowired
    private SysDepartmentMapper sysDepartmentMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    public Map<Long, List<SysOrganization>> groupByPid(){
        Map<Long, List<SysOrganization>> map = new HashMap<>();
        List<SysOrganization> list = sysOrganizationMapper.selectAll();
        if(CollectionUtil.isNotEmpty(list)){
            for (SysOrganization organization : list) {
                Long key = organization.getId();
                if(map.containsKey(key)){
                    List<SysOrganization> children = map.get(key);
                    children.add(organization);
                    map.put(key,children);
                }else{
                    List<SysOrganization> children = map.get(key);
                    children.add(organization);
                    map.put(key,children);
                }
            }
        }
        return map;
    }


    public Map<Long, List<SysOrganization>> groupByPid(final Map<Long,SysOrganization> organizationMap){
        Map<Long, List<SysOrganization>> map = new HashMap<>();
        if(CollectionUtil.isNotEmpty(organizationMap)){
            Set<Map.Entry<Long, SysOrganization>> entrySet = organizationMap.entrySet();
            for (Map.Entry<Long, SysOrganization> longSysOrganizationEntry : entrySet) {
                SysOrganization value = longSysOrganizationEntry.getValue();
                Long key = value.getPid();
                if(map.containsKey(key)){
                    List<SysOrganization> children = map.get(key);
                    children.add(value);
                    map.put(key,children);
                }else{
                    List<SysOrganization> children = new ArrayList<>();
                    children.add(value);
                    map.put(key,children);
                }
            }
        }
        return map;
    }

    /**
     * 根据userId构建其组织结构
     * @param userType
     * @param userId
     * @return
     */
    public JSONObject buildOrgnizationByUserId(String userType, Long userId, Long agentId,Long parenCompanyId,Long branchCompanyId,Long projectId){
        JSONObject result = new JSONObject();
        if("A100403".equals(userType)) { // 代理商管理账号
            final Map<Long,SysOrganization> organizationMap = getAllByCompanyId("A101101",agentId);
            final Map<Long, List<SysOrganization>> groupByPid = groupByPid(organizationMap);

            if(organizationMap == null || organizationMap.size() == 0){
                return  result;
            }

            if(groupByPid == null || groupByPid.size() == 0){
                return  result;
            }

            SysCompany company = sysCompanyMapper.selectByPrimaryKey(agentId);
            if(company != null){
                result.put("name",company.getName() + "[代理商]");

                SysOrganization organizationSearch = new SysOrganization();
                organizationSearch.setRelationId(company.getId());
                organizationSearch.setType("A101101");
                SysOrganization root = sysOrganizationMapper.selectOne(organizationSearch);
                if(root != null){
                    List<SysOrganization> childrenList = groupByPid.get(root.getId());
                    if(CollectionUtil.isNotEmpty(childrenList)){
                        JSONArray rootChildren = new JSONArray(childrenList.size());
                        for (SysOrganization organization : childrenList) {
                            String type = organization.getType();
                            Long relationId = organization.getRelationId();
                            String name = getName(type,relationId);
                            final JSONObject child = new JSONObject();
                            child.put("name",name);
                            lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                            rootChildren.add(child);
                        }
                        result.put("children",rootChildren);
                    }
                }
            }
        }else if("A100406".equals(userType)){ // 总公司账号
            final Map<Long,SysOrganization> organizationMap = getAllByCompanyId("A101104",parenCompanyId);
            final Map<Long, List<SysOrganization>> groupByPid = groupByPid(organizationMap);

            if(organizationMap == null || organizationMap.size() == 0){
                return  result;
            }

            if(groupByPid == null || groupByPid.size() == 0){
                return  result;
            }

            SysCompany company = sysCompanyMapper.selectByPrimaryKey(parenCompanyId);
            if(company != null){
                result.put("name",company.getName() + "[总公司]");

                SysOrganization organizationSearch = new SysOrganization();
                organizationSearch.setRelationId(company.getId());
                organizationSearch.setType("A101104");
                SysOrganization root = sysOrganizationMapper.selectOne(organizationSearch);
                if(root != null){
                    List<SysOrganization> childrenList = groupByPid.get(root.getId());
                    if(CollectionUtil.isNotEmpty(childrenList)){
                        JSONArray rootChildren = new JSONArray(childrenList.size());
                        for (SysOrganization organization : childrenList) {
                            String type = organization.getType();
                            Long relationId = organization.getRelationId();
                            String name = getName(type,relationId);
                            final JSONObject child = new JSONObject();
                            child.put("name",name);
                            lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                            rootChildren.add(child);
                        }
                        result.put("children",rootChildren);
                    }
                }
            }
        }else if("A100409".equals(userType)){ // 分公司账号
            final Map<Long,SysOrganization> organizationMap = getAllByCompanyId("A101107",branchCompanyId);
            final Map<Long, List<SysOrganization>> groupByPid = groupByPid(organizationMap);

            if(organizationMap == null || organizationMap.size() == 0){
                return  result;
            }

            if(groupByPid == null || groupByPid.size() == 0){
                return  result;
            }

            SysCompany company = sysCompanyMapper.selectByPrimaryKey(branchCompanyId);
            if(company != null){
                result.put("name",company.getName() + "[分公司]");

                SysOrganization organizationSearch = new SysOrganization();
                organizationSearch.setRelationId(company.getId());
                organizationSearch.setType("A101107");
                SysOrganization root = sysOrganizationMapper.selectOne(organizationSearch);
                if(root != null){
                    List<SysOrganization> childrenList = groupByPid.get(root.getId());
                    if(CollectionUtil.isNotEmpty(childrenList)){
                        JSONArray rootChildren = new JSONArray(childrenList.size());
                        for (SysOrganization organization : childrenList) {
                            String type = organization.getType();
                            Long relationId = organization.getRelationId();
                            String name = getName(type,relationId);
                            final JSONObject child = new JSONObject();
                            child.put("name",name);
                            lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                            rootChildren.add(child);
                        }
                        result.put("children",rootChildren);
                    }
                }
            }
        }else if("A100410".equals(userType)){ // 项目账号
            final Map<Long,SysOrganization> organizationMap = getAllByProjectId("A101109",projectId);
            final Map<Long, List<SysOrganization>> groupByPid = groupByPid(organizationMap);

            if(organizationMap == null || organizationMap.size() == 0){
                return  result;
            }

            if(groupByPid == null || groupByPid.size() == 0){
                return  result;
            }

            SysProject project = sysProjectMapper.selectByPrimaryKey(projectId);
            if(project != null){
                result.put("name",project.getName() + "[项目]");

                SysOrganization organizationSearch = new SysOrganization();
                organizationSearch.setRelationId(project.getId());
                organizationSearch.setType("A101109");
                SysOrganization root = sysOrganizationMapper.selectOne(organizationSearch);
                if(root != null){
                    List<SysOrganization> childrenList = groupByPid.get(root.getId());
                    if(CollectionUtil.isNotEmpty(childrenList)){
                        JSONArray rootChildren = new JSONArray(childrenList.size());
                        for (SysOrganization organization : childrenList) {
                            String type = organization.getType();
                            Long relationId = organization.getRelationId();
                            String name = getName(type,relationId);
                            final JSONObject child = new JSONObject();
                            child.put("name",name);
                            lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                            rootChildren.add(child);
                        }
                        result.put("children",rootChildren);
                    }
                }
            }
        }else if("A100411".equals(userType)) { // 业务员
            final Map<Long,SysOrganization> organizationMap = getAllByUserId(userId);
            final Map<Long, List<SysOrganization>> groupByPid = groupByPid(organizationMap);

            if(organizationMap == null || organizationMap.size() == 0){
                return  result;
            }

            if(groupByPid == null || groupByPid.size() == 0){
                return  result;
            }


            SysCompany branchCompany = sysCompanyMapper.selectByPrimaryKey(branchCompanyId);
            if(branchCompany != null){
                result.put("name",branchCompany.getName() + "[公司]");

                SysOrganization organizationSearch = new SysOrganization();
                organizationSearch.setRelationId(branchCompany.getId());
                organizationSearch.setType("A101107");
                SysOrganization root = sysOrganizationMapper.selectOne(organizationSearch);
                if(root != null){
                    List<SysOrganization> childrenList = groupByPid.get(root.getId());
                    if(CollectionUtil.isNotEmpty(childrenList)){
                        JSONArray rootChildren = new JSONArray(childrenList.size());
                        for (SysOrganization organization : childrenList) {
                            String type = organization.getType();
                            Long relationId = organization.getRelationId();
                            String name = getName(type,relationId);
                            final JSONObject child = new JSONObject();
                            child.put("name",name);
                            lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                            rootChildren.add(child);
                        }
                        result.put("children",rootChildren);
                    }
                }
            }
        }
        return result;
    }

    private void lookupBuildOrgnizationChild(final Map<Long, List<SysOrganization>> groupByPid,final JSONObject jsonObject,Long id){
        List<SysOrganization> childrenList = groupByPid.get(id);
        if(CollectionUtil.isNotEmpty(childrenList)){
            JSONArray children = new JSONArray(childrenList.size());
            for (SysOrganization organization : childrenList) {
                String type = organization.getType();
                Long relationId = organization.getRelationId();
                String name = getName(type,relationId);
                final JSONObject child = new JSONObject();
                child.put("name",name);
                lookupBuildOrgnizationChild(groupByPid,child,organization.getId());
                children.add(child);
            }
            jsonObject.put("children",children);
        }
    }


    /**
     * 根据companyId获取其所有组织信息
     * @param companyId
     * @return
     */
    private Map<Long,SysOrganization> getAllByCompanyId(String type,Long companyId){
        final Map<Long,SysOrganization> result = new HashMap<>();
        SysOrganization organizationSearch = new SysOrganization();
        organizationSearch.setRelationId(companyId);
        organizationSearch.setType(type);
        List<SysOrganization> organizationList = sysOrganizationMapper.select(organizationSearch);
        if(CollectionUtil.isNotEmpty(organizationList)){
            for (SysOrganization organization : organizationList) {
                if(!result.containsKey(organization.getId())){
                    result.put(organization.getId(),organization);
                }
                lookupChild(result,organization.getId());
            }
        }
        return result;
    }


    /**
     * 根据projectId获取其所有组织信息
     * @param projectId
     * @return
     */
    private Map<Long,SysOrganization> getAllByProjectId(String type,Long projectId){
        final Map<Long,SysOrganization> result = new HashMap<>();
        SysOrganization organizationSearch = new SysOrganization();
        organizationSearch.setRelationId(projectId);
        organizationSearch.setType(type);
        List<SysOrganization> organizationList = sysOrganizationMapper.select(organizationSearch);
        if(CollectionUtil.isNotEmpty(organizationList)){
            for (SysOrganization organization : organizationList) {
                if(!result.containsKey(organization.getId())){
                    result.put(organization.getId(),organization);
                }
                lookupChild(result,organization.getId());
            }
        }
        return result;
    }


    /**
     * 根据userId获取其所有组织信息
     * @param userId
     * @return
     */
    private Map<Long,SysOrganization> getAllByUserId(Long userId){
        final Map<Long,SysOrganization> result = new HashMap<>();
        SysOrganization organizationSearch = new SysOrganization();
        organizationSearch.setRelationId(userId);
        organizationSearch.setType("A101115");
        List<SysOrganization> organizationList = sysOrganizationMapper.select(organizationSearch);
        if(CollectionUtil.isNotEmpty(organizationList)){
            for (SysOrganization organization : organizationList) {
                if(!result.containsKey(organization.getId())){
                    result.put(organization.getId(),organization);
                }
                lookupParent(result,organization.getPid());
            }
        }
        return result;
    }

    private void lookupParent(final Map<Long,SysOrganization> result,Long id){
        if(id != null){
            SysOrganization parent = sysOrganizationMapper.selectByPrimaryKey(id);
            if(parent != null){
                if(!result.containsKey(parent.getId())){
                    result.put(parent.getId(),parent);
                }
                lookupParent(result,parent.getPid());
            }
        }
    }

    private void lookupChild(final Map<Long,SysOrganization> result,Long id){
        SysOrganization organizationSearch = new SysOrganization();
        organizationSearch.setPid(id);
        List<SysOrganization> children = sysOrganizationMapper.select(organizationSearch);
        if(CollectionUtil.isNotEmpty(children)){
            for (SysOrganization child : children) {
                if(!result.containsKey(child.getId())){
                    result.put(child.getId(),child);
                }
                lookupChild(result,child.getId());
            }
        }
    }

    private String getName(String type,Long relationId){
        String name = "";
        if("A101101".equals(type)){ // 代理商
            SysCompany company = sysCompanyMapper.selectByPrimaryKey(relationId);
            if(company != null){
                name = company.getName() + "[代理商]";
            }
        }else if("A101104".equals(type)){ // 总公司
            SysCompany company = sysCompanyMapper.selectByPrimaryKey(relationId);
            if(company != null){
                name = company.getName() + "[总公司]";
            }
        }else if("A101107".equals(type)){ // 分公司
            SysCompany company = sysCompanyMapper.selectByPrimaryKey(relationId);
            if(company != null){
                name = company.getName() + "[分公司]";
            }
        }else if("A101109".equals(type)){ // 项目
            SysProject project = sysProjectMapper.selectByPrimaryKey(relationId);
            if(project != null){
                name = project.getName() + "[项目]";
            }
        }else if("A101111".equals(type)){ // 部门
            SysDepartment department = sysDepartmentMapper.selectByPrimaryKey(relationId);
            if(department != null){
                name = department.getName() + "[部门]";
            }
        }else if("A101113".equals(type)){ // 岗位
            SysRole role = sysRoleMapper.selectByPrimaryKey(relationId);
            if(role != null){
                name = role.getName() + "[岗位]";
            }
        }else if("A101115".equals(type)){ // 职工
            SysUser user = sysUserMapper.selectByPrimaryKey(relationId);
            if(user != null){
                name = user.getRealName() + "[员工]";
            }
        }
        return name;
    }
}
